//
//  DatePickerViewController.swift
//  Dimmer
//
//  Created by 郑林琴 on 2017/2/17.
//  Copyright © 2017年 IB. All rights reserved.
//

import UIKit
import ReactiveSwift
import Result


typealias DateResult = (Date) -> ()

extension T {
    
    static func showDatePicker(from: UIViewController, minNow: Bool, pickerMode: UIDatePickerMode? = .date) -> SignalProducer<Date, NoError> {
        
        return SignalProducer.init({ [unowned from] (observer, dispose) in
            
            let picker = DatePickerViewController()
            
            if minNow {
                picker.datePicker.maximumDate = Date()
            }
            if let mode = pickerMode {
                picker.datePicker.datePickerMode = mode
            }
            picker.dateCallback = { d in
                observer.send(value: d)
                observer.sendCompleted()
            }
            picker.reactive.lifetime.ended.observeCompleted {
                observer.sendInterrupted()
            }
            from.present(picker, animated: true, completion: nil)
        })
    }
}


class DatePickerViewController: BIActionsDimmerViewController {
    
    let datePicker = UIDatePicker()

    var dateCallback: DateResult?

    override func viewDidLoad() {
        super.viewDidLoad()

        var frame = self.containerView.frame
        frame.origin.y = 44
        frame.size.height   -= 44
        self.datePicker.frame = frame
        self.containerView.addSubview(datePicker)
    }
    
    override func confirmActioned() {
        self.dateCallback?(self.datePicker.date)
        self.dismiss(animated: true, completion: nil)
    }
}
